package cn.com.homeyoda.aimate.aihealth.ui.health;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.annotation.RequiresApi;
import androidx.databinding.library.baseAdapters.BR;
import androidx.lifecycle.ViewModelProviders;

import com.wzq.mvvmsmart.event.StateLiveData;
import com.wzq.mvvmsmart.utils.GlideLoadUtils;
import com.wzq.mvvmsmart.utils.ToastUtils;

import cn.com.homeyoda.aimate.aihealth.R;
import cn.com.homeyoda.aimate.aihealth.app.AppViewModelFactory;
import cn.com.homeyoda.aimate.aihealth.base.BaseActivity;
import cn.com.homeyoda.aimate.aihealth.bean.FamilyMembersBean;
import cn.com.homeyoda.aimate.aihealth.databinding.ActivitySportPlanBinding;
import cn.com.homeyoda.aimate.aihealth.manager.UserInfoManager;
import cn.com.homeyoda.aimate.aihealth.ui.health.frragment.MyPlanFragment;
import cn.com.homeyoda.aimate.aihealth.ui.health.frragment.SportPlanFragment;
import cn.com.homeyoda.aimate.aihealth.ui.health.viewModel.SportPlanViewModel;
import cn.com.homeyoda.aimate.aihealth.ui.my.MyActivity;
import cn.com.homeyoda.aimate.aihealth.views.CenterDialog;
import cn.com.homeyoda.aimate.aihealth.views.MemberChangeDialog;

/**
 * 运动计划界面
 */
public class SportPlanActivity extends BaseActivity<ActivitySportPlanBinding, SportPlanViewModel> {


    private MemberChangeDialog memberChangeDialog;

    private SportPlanFragment sportPlanFragment = new SportPlanFragment();
    private MyPlanFragment myPlanFragment = new MyPlanFragment();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    private void jump() {
        if (UserInfoManager.getInstance().isJoinPlan()) {
            changeMyPlanFragment();
        } else {
            changeMoreFragment();
        }
    }

    public void changeMoreFragment() {
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.sport_fragment, sportPlanFragment) // 添加到容器
                .commit();
    }

    public void changeMyPlanFragment() {
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.sport_fragment, myPlanFragment) // 添加到容器
                .commit();
    }

    @Override
    public SportPlanViewModel initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(SportPlanViewModel.class);
    }

    @Override
    public void initData() {
        super.initData();
        initView();
        viewModel.initUserInfo();
        viewModel.initPlanInfo();
    }

    private void initView() {


        binding.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });


        binding.tvTitle.setText(R.string.stort_plan);

        binding.btnChangeMember.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (viewModel.planUserStateLiveData.getValue() == null) {
                    ToastUtils.showLong("成员未初始化，请稍后重试");
                    return;
                }

                if (memberChangeDialog == null) {
                    memberChangeDialog = new MemberChangeDialog(SportPlanActivity.this, viewModel.familyMembers, viewModel.planUserStateLiveData.getValue().getId()
                            , new MemberChangeDialog.SelectClickListener() {
                        @Override
                        public void onSelectMember(FamilyMembersBean.DataBean.FamilyMembers member) {
                            if (member != null && member.getId() != viewModel.planUserStateLiveData.getValue().getId()) {
                                viewModel.changeMember(member);
                            }
                        }
                    });
                } else {
                    memberChangeDialog.setDatas(viewModel.familyMembers, viewModel.planUserStateLiveData.getValue().getId());
                }

                memberChangeDialog.show();
            }
        });

        binding.btnAddMember.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(MyActivity.class);
                finish();
            }
        });
    }


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    public void querySportPlans(String planType) {
        viewModel.querySportPlans(planType);
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.planUserStateLiveData.observe(this, userBean -> {
            binding.setPlanUserBean(userBean);
            GlideLoadUtils.loadImg(binding.crvHead, userBean.getAvatar(), R.mipmap.ic_member1);
            viewModel.hasSelfPlan();
        });

        viewModel.planUserStateLiveData.stateEnumMutableLiveData.observe(this, state -> {
            Log.d("pangtao", "stateEnumMutableLiveData state = " + state);
            if (state == StateLiveData.StateEnum.Error) {
                binding.clNotUser.setVisibility(View.VISIBLE);
                binding.clUserInfo.setVisibility(View.INVISIBLE);
                binding.emptyView.setVisibility(View.VISIBLE);
                binding.sportFragment.setVisibility(View.INVISIBLE);
            } else if (state == StateLiveData.StateEnum.Success) {
                binding.sportFragment.setVisibility(View.VISIBLE);
                binding.emptyView.setVisibility(View.GONE);
                binding.clNotUser.setVisibility(View.INVISIBLE);
                binding.clUserInfo.setVisibility(View.VISIBLE);
            }
        });

        viewModel.planTitleStateLiveData.observe(this, planTitleBeans -> {
            sportPlanFragment.updateTitle(planTitleBeans);
        });

        viewModel.planStateLiveData.observe(this, planBeans -> {
            sportPlanFragment.upDateContent(planBeans);
        });

        viewModel.weekList.observe(this, weekList -> {
            if (myPlanFragment != null) {
                myPlanFragment.updateWeek(weekList);
            }
        });

        viewModel.mWeek.observe(this, week -> {
            if (myPlanFragment != null) {
                myPlanFragment.setWeek(week);
            }
        });

        viewModel.joinPlanStateLiveData.observe(this, state -> {
            if (myPlanFragment != null) {
                myPlanFragment.upDateUi();
            }
        });

        viewModel.myselfPlanBeanStateLiveData.observe(this, myselfPlanBean -> {
            jump();
        });

        viewModel.planDetailsLiveData.observe(this, dataBean -> {
            if (myPlanFragment != null) {
                myPlanFragment.upDateVideoList(dataBean.getSubjectList());
            }
        });

    }

    public void caclePlan(String faceId, String planId) {
        CenterDialog dialog = new CenterDialog(this, getResources().getString(R.string.cacle_plan_message), new CenterDialog.SureClickListener() {
            @Override
            public void sureClick() {
                viewModel.unJoinPlan(faceId, planId);
            }
        });

        dialog.show();
    }

    public SportPlanViewModel getViewModel(){
        return viewModel;
    }

    public void initWeek() {
        viewModel.initWeek();
    }

    public void setWeek(int week) {
        if (UserInfoManager.getInstance().selfSportPlan != null) {
            viewModel.setWeek(viewModel.planUserStateLiveData.getValue().getFaceId(), UserInfoManager.getInstance().selfSportPlan.getPlanId(), week);
        }
    }

    public String getFaceId() {
        return viewModel.planUserStateLiveData.getValue().getFaceId();
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_sport_plan;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }
}
